package com.mazaiting.redeye.module.friend

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import cn.jpush.im.android.api.ContactManager
import cn.jpush.im.android.api.callback.GetUserInfoListCallback
import cn.jpush.im.android.api.event.ContactNotifyEvent
import cn.jpush.im.android.api.model.UserInfo
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.SectionEntity
import com.mazaiting.easy.app.IApplicationComponent
import com.mazaiting.easy.base.fragment.BaseRefreshFragment
import com.mazaiting.log.L
import com.mazaiting.redeye.R
import com.mazaiting.redeye.base.ApplicationComponentImpl
import com.mazaiting.redeye.module.friend.add.AddFriendActivity
import com.mazaiting.redeye.module.friend.add.AddFriendPassiveActivity
import com.mazaiting.redeye.module.msg.single.SingleActivity
import com.mazaiting.redeye.utils.NotificationUtil
import com.mazaiting.redeye.utils.PinYinHelper
import com.mazaiting.redeye.utils.SortComparator
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.regex.Pattern
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.Executors
import kotlin.Comparator


/**
 * 好友碎片
 */
class FriendFragment : BaseRefreshFragment<FriendPresenter>(), FriendContract.View {

    companion object {

        @JvmStatic
        fun newInstance() = FriendFragment()
    }

    override fun bindView(view: View?, savedInstanceState: Bundle?) {
        super.bindView(view, savedInstanceState)
        EventBus.getDefault().register(this)
        swipeLayout.isEnabled = false
        initHeaderView()
        initBodyView()
    }

    /**
     * 初始化内容布局
     */
    private fun initBodyView() {
        // 设置条目点击
        adapter.setOnItemClickListener { adapter, _, position ->
            // 获取用户信息
            val sectionEntity = adapter.getItem(position) as SectionEntity<*>
            // 如果不是头部
            if (!sectionEntity.isHeader && null != context) {
                SingleActivity.newInstance(context!!, (sectionEntity.t as UserInfo).userName)
            }
            // 如果是头部
            if (sectionEntity.isHeader) {
                Toast.makeText(context, "头部${ sectionEntity.header} 点击", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 初始化头部视图
     */
    @SuppressLint("InflateParams")
    private fun initHeaderView() {
        // 加载布局
        val headerView = layoutInflater.inflate(R.layout.friend_header, null)
        // 获取新朋友条目
        val btnNewFriend:ConstraintLayout = headerView.findViewById(R.id.friend_header_new_friend)
        // 设置点击事件
        btnNewFriend.setOnClickListener {
            if (null != context) {
                AddFriendActivity.newInstance(context!!)
            }
        }
        adapter.setHeaderView(headerView)
    }

    override fun lazyFetchData() {
        // 获取好友列表
        ContactManager.getFriendList(object : GetUserInfoListCallback() {
            override fun gotResult(code: Int, msg: String?, list: MutableList<UserInfo>?) {
                L.d("code: $code, msg: $msg, list: $list")
//                val userInfoList = CopyOnWriteArrayList<SectionEntity<UserInfo>>()
                if (!list.isNullOrEmpty()) {
                    // 线程池
                    val service = Executors.newSingleThreadExecutor()
                    service.execute {
                        // 获取用户信息
                        val userInfoList = SortComparator.getUserInfoList(list)
                        activity?.runOnUiThread {
                            adapter.setNewData(userInfoList)
                        }
                    }
                }
            }
        })
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onContactNotifyEvent(event: ContactNotifyEvent) {
        L.d("好友通知")
        // 原因
        val reason = event.reason
        // 用户
        val username = event.fromUsername
        when (event.type) {
            // 收到好友邀请
            ContactNotifyEvent.Type.invite_received -> {
                // 意图
                val intent = AddFriendPassiveActivity.getPendingIntent(context!!, username, reason)
                // 延时意图
                val pendingIntent = NotificationUtil.getContentIntent(context!!, intent)
                // 发送通知
                NotificationUtil.sendNotification(
                    context!!,
                    System.currentTimeMillis().toInt(),
                    "好友通知",
                    "${username}请求添加好友",
                    "有新通知到来",
                    pendingIntent
                )
            }
            // 对方接收了你的好友邀请
            ContactNotifyEvent.Type.invite_accepted -> {
                // 发送通知
                NotificationUtil.sendNotification(
                    context!!,
                    System.currentTimeMillis().toInt(),
                    "好友通知",
                    "${username}接受了您的好友请求",
                    "有新通知到来"
                )
            }
            // 对方拒绝了你的好友邀请
            ContactNotifyEvent.Type.invite_declined -> {
                // 发送通知
                NotificationUtil.sendNotification(
                    context!!,
                    System.currentTimeMillis().toInt(),
                    "好友通知",
                    "${username}拒绝与您加为好友",
                    "有新通知到来"
                )
            }
            // 对方将你从好友中删除
            ContactNotifyEvent.Type.contact_deleted -> {
                // 发送通知
                NotificationUtil.sendNotification(
                    context!!,
                    System.currentTimeMillis().toInt(),
                    "好友通知",
                    "${username}已将您从好友列表中移除",
                    "有新通知到来"
                )
            }
            else -> {
                Toast.makeText(context, "未知好友事件类型", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun getContentLayout(): Int = R.layout.fragment_friend

    override fun inject(applicationComponent: IApplicationComponent?) {
        DaggerFriendComponent
            .builder()
            .applicationComponentImpl(applicationComponent as ApplicationComponentImpl)
            .build()
            .inject(this)
    }

    override fun setAdapter(): BaseQuickAdapter<*, *> = FriendAdapter()

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

}

